import React, { FC, useMemo, useState, useEffect, useCallback } from 'react';
import { groupBy } from 'lodash'
import { PlaneTrip, Plane } from '../types/plane.type';
import { SchedulingForm } from './SchedulingForm';
import { getTripsByPlaneId, getAllPlaneTrip } from '@apis/index';
import { SchedulingGrid } from './SchedulingGrid';

import './Scheduling.css';

type Props = {
    selectedPlane?: Plane;
}

const TIME_OUT = 60000;
let timer: NodeJS.Timeout;

export const Scheduling: FC<Props> = ({ selectedPlane }) => {
    const [trips, setTrips] = useState<PlaneTrip[]>([]);
    const init = useCallback(() => {
        if (timer) clearTimeout(timer);
        if (!selectedPlane) {
            getAllPlaneTrip().then(setTrips);
            timer = setTimeout(init, TIME_OUT)
            return;
        }
        getTripsByPlaneId(selectedPlane?.id!).then(setTrips)
        timer = setTimeout(init, TIME_OUT)
    }, [selectedPlane])
    useEffect(() => {
        init();
        return () => {
            if (timer) clearTimeout(timer);
        }
    }, [init]);
    const formatedTrips = useMemo(() => {
        const tripsMap = groupBy(trips, 'plane.id')
        return {
            tripsMap,
            planeIds: Object.keys(tripsMap)
        }
    }, [trips])
    return <div className='schedulingWrapper'>
        <SchedulingForm selectedPlane={selectedPlane} afterSubmit={init} />
        <SchedulingGrid formatedTrips={formatedTrips} init={init} />
    </div>
}
